import re

word = {}  # 字的字典集
total = 0  # 字的总数
middle = {}  # 中间临时排序统计
result = {}  # 最终的结果


# 读取文件里的内容，进行初步的字的统计
def fileProcess():
    global total
    f = open("./test.txt", "r", encoding="utf-8")
    # print("进行统计ing")
    for line in f:
        # 读取文件里每一行的内容
        line = line.split("\n")[0]  # 将换行符进行分割开
        for char in line:
            # and "\n"
            if char != " ":
                total += 1
                if char in word:
                    word[char]['number'] += 1
                else:
                    word[char] = {}
                    word[char]['number'] = 1
    # for item in word:
    #     print(item + str(word[item]))


# 进行排序
def Sort():
    global middle
    # 进行排序，按照出现的次数进行排序，出现次数多的在前
    y1 = {k: v for k, v in sorted(word.items(), key=lambda item: item[1]["number"], reverse=True)}
    base_char = next(iter(y1))
    number = y1[base_char]["number"]
    for item in y1:
        if y1[item]['number'] == number:
            middle[item] = {}
            middle[item]["number"] = y1[item]["number"]
        else:
            # 进行排序，按照字符小的在前
            y2 = {k: v for k, v in sorted(middle.items(), key=lambda item: item[0])}
            result.update(y2)
            middle = {}
            middle[item] = {}
            middle[item]["number"] = y1[item]["number"]
            number = y1[item]['number']
    y2 = {k: v for k, v in sorted(middle.items(), key=lambda item: item[0])}
    result.update(y2)
    # for item in result:
    # print(item + str(result[item]))


# 输出统计的结果
def output():
    for char in result:
        result[char]["probability"] = float(result[char]["number"] / total)
        # 输出的规定形式
        print(char + "\t:\t " + str(result[char]["probability"] * 100)[0:4] + "%")


fileProcess()
Sort()
output()
